package com.chianghao.qyt.controller.manage_api;


import com.chianghao.frame.core.auth.AuthRequestContext;
import com.chianghao.qyt.controller.manage_api.dto.MenuTreeVo;
import com.chianghao.qyt.controller.manage_api.vo.MenuVo;
import com.chianghao.qyt.entity.SysOperationMenu;
import com.chianghao.qyt.service.SysOperationAdminService;
import com.chianghao.qyt.service.SysOperationMenuService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("manage/api/operation-menu")
public class SysOperationMenuController {


    @Resource
    SysOperationMenuService sysOperationMenuService;

    @Resource
    SysOperationAdminService sysOperationAdminService;

    @GetMapping("tree")
    @Operation(summary = "查询所有菜单")
    public List<MenuTreeVo> query() {
        List<SysOperationMenu> menus = sysOperationMenuService.allMenus();
        return toTree(menus,"0");
    }


    @GetMapping("login/menus")
    public List<MenuVo> getAdminMenu(){
        Long userId = Long.parseLong(AuthRequestContext.getUserId());
        List<SysOperationMenu> menus = null;
        if(sysOperationAdminService.isSupperAdmin(userId)){
            menus = sysOperationMenuService.allMenus();
        }else{
            menus = sysOperationMenuService.loadUserMenus(userId);
        }
        return menus.stream().map(i->{
            MenuVo m = new MenuVo();
            setMenuVoValue(i,m);
            return m;
        }).toList();
    }


    private List<MenuTreeVo> toTree(List<SysOperationMenu> list, String parenId) {
        List<MenuTreeVo> menuTreeVos = new ArrayList<>();
        for (SysOperationMenu v : list) {
            if(v.getParentId().equals(parenId)) {
                MenuTreeVo item = new MenuTreeVo();
                setMenuVoValue(v,item);
                List<MenuTreeVo> ch = toTree(list,v.getId());
                if(!ch.isEmpty()) {
                    item.setChildren(ch);
                }
                menuTreeVos.add(item);
            }
        }
        return menuTreeVos;
    }


    public <T extends MenuVo> void setMenuVoValue(SysOperationMenu entity,T vo){
        vo.setId(entity.getId());
        vo.setParentId(entity.getParentId());
        vo.setName(entity.getName());
        vo.setIcon(entity.getIcon());
        vo.setUrl(entity.getUrl());
        vo.setType(entity.getType());
        vo.setSort(entity.getSort());
    }




}
